package notification

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"

	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateNotificationLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUpdateNotificationLogic 更新通知
func NewUpdateNotificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateNotificationLogic {
	return &UpdateNotificationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateNotificationLogic) UpdateNotification(req *types.UpdateNotificationRequest) (resp *types.UpdateNotificationResponse, err error) {
	// 查找通知记录
	existingNotification, err := l.svcCtx.NotificationModel.FindOne(req.Notification.ID)
	if err != nil {
		if errors.Is(err, sqlc.ErrNotFound) {
			logx.Errorf("更新数据失败...")
			return &types.UpdateNotificationResponse{
				Success: 500,
				Message: fmt.Sprintf("Notification not found with ID: %d", req.Notification.ID),
				Error:   err.Error(),
			}, err
		}

		l.Logger.Errorf("查找通知记录失败，ID: %d, 错误: %v", req.Notification.ID, err)
		return &types.UpdateNotificationResponse{
			Success: 500,
			Message: "Failed to find notification",
			Error:   err.Error(),
		}, err
	}

	// 将 config 字段序列化为 JSON 字符串
	configBytes, err := json.Marshal(req.Notification.Config)
	if err != nil {
		logx.Errorf("将配置字段转换为 JSON 字符串失败，ID: %d, 错误: %v", req.Notification.ID, err)
		return &types.UpdateNotificationResponse{
			Success: 500,
			Message: "解析通知配置失败",
			Error:   err.Error(),
		}, err
	}

	// 更新通知记录的字段
	existingNotification.Type = req.Notification.Type
	existingNotification.Config = string(configBytes)

	// 更新数据库中的通知记录
	err = l.svcCtx.NotificationModel.Update(existingNotification)
	if err != nil {
		logx.Errorf("更新通知记录失败，ID: %d, 错误: %v", req.Notification.ID, err)
		return &types.UpdateNotificationResponse{
			Success: 500,
			Message: "Failed to update notification",
			Error:   err.Error(),
		}, err
	}

	// 返回更新成功的详细信息
	return &types.UpdateNotificationResponse{
		Success:             200,
		Message:             "通知配置更新成功",
		UpdatedNotification: existingNotification,
	}, nil
}
